package com.ftg.learn.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ftg.learn.system.entity.Dept;
import com.ftg.learn.system.mapper.DeptMapper;
import com.ftg.learn.system.service.IDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftg.learn.system.vo.OrganizationVo;
import com.ftg.learn.util.ConstUtil;
import com.ftg.learn.util.JsonWeb;
import com.ftg.learn.util.JsonWebUtil;
import com.ftg.learn.util.TreeUtil;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author kangjx
 * @since 2023-05-09
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {

    /**
     * 组织结构树
     * @return
     */
    @Override
    public JsonWeb<List<OrganizationVo>> organizationList() {
        LambdaQueryWrapper<Dept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dept::getParentId, ConstUtil.ROOTID);
        List<Dept> depts = this.list(queryWrapper);

        TreeUtil<Dept, OrganizationVo> treeUtil = new TreeUtil<>(list(), OrganizationVo.class);
        List<OrganizationVo> deptTreeVos = depts.stream()
                .map(dept -> {
                    try {
                        return treeUtil.getTreeNode(dept.getId());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                })
                .collect(Collectors.toList());
        return JsonWebUtil.success(deptTreeVos);
    }
}
